package com.main.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mobile.device.DeviceUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.main.dao.UploaderDAO;
import com.main.pojo.Response;
import com.main.pojo.TrollPhoto;
import com.main.pojo.Uploader;
import com.main.utils.CommonUtils;
import com.main.utils.Constant;

@Controller
@RequestMapping("/uploader/**")
@SessionAttributes("uploader")
public class UploaderController {

	private static final Logger logger = LoggerFactory.getLogger(UploaderController.class);

	@Autowired
	private UploaderDAO uploaderDao;

	public UploaderDAO getUploaderDao() {
		return uploaderDao;
	}

	public void setUploaderDao(UploaderDAO uploaderDao) {
		this.uploaderDao = uploaderDao;
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String uploader(@PathVariable int id, Model model, HttpServletRequest request) {
		String path = "";
		try {
			model.addAttribute("selectUploader", uploaderDao.getUploaderById(id));
			model.addAttribute("trollList", new ArrayList<TrollPhoto>());
			path = CommonUtils.getRootPathByDevice(DeviceUtils.getCurrentDevice(request));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return path + "uploaderDetail";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public @ResponseBody
	Response login(@RequestParam(value = "email") String email, @RequestParam(value = "name") String name,
			@RequestParam(value = "avatar", required = false) String avatar, HttpServletRequest request, Model model) {
		Response result = new Response();
		try {
			Uploader uploader = uploaderDao.getUploaderByEmail(email);
			if (uploader == null) {
				// copy avatar from facebook
				int lastIndex = avatar.lastIndexOf(".");
				String fileType = avatar.substring(lastIndex, lastIndex + 4);
				Date date = new Date();
				String randomFileName = String.valueOf(date.getTime()) + String.valueOf(Math.random()).replace(".", "")
						+ fileType;
				String path = request.getSession().getServletContext().getRealPath("/") + Constant.AVATAR_PATH;
				path = path + "/" + randomFileName;
				FileUtils.copyURLToFile(new URL(avatar), new File(path));
				avatar = request.getContextPath() + "/" + Constant.AVATAR_PATH + "/" + randomFileName;
				uploader = uploaderDao.insertUploader(email, name, avatar);
			}
			// request.getSession().setAttribute("uploader", uploader);
			model.addAttribute("uploader", uploader);
			result.setData(uploader);
		} catch (Exception e) {
			result.setSuccess(false);
			e.printStackTrace();
		}
		return result;

	}
	
	@RequestMapping(value = "/login-account", method = RequestMethod.POST)
	public @ResponseBody
	Response loginWithAccount(@RequestParam(value = "email") String email, @RequestParam(value = "password") String password, Model model) {
		Response result = new Response();
		try {
			Uploader uploader = uploaderDao.getUploader(email, password);
			if(uploader != null){
				model.addAttribute("uploader", uploader);
				result.setData(uploader);
			}
		} catch (Exception e) {
			result.setSuccess(false);
			e.printStackTrace();
		}
		return result;

	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(Model model) {
		return "login";
	}

	@RequestMapping(value = "/info", method = RequestMethod.GET)
	public String uploaderInfo(Model model, HttpServletRequest request) {
		try {
			Uploader uploader = (Uploader) request.getSession().getAttribute("uploader");
			if(uploader == null){
				return "redirect:/uploader/login";
			}
			Uploader currentUploader = uploaderDao.getUploaderById(uploader.getId());
			model.addAttribute("currentUploader", currentUploader);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "uploaderInfo";
	}

	@RequestMapping(value = "/change-password", method = RequestMethod.GET)
	public String changePassword(HttpServletRequest request,Model model) {
		Uploader uploader = (Uploader) request.getSession().getAttribute("uploader");
		if(uploader == null){
			return "redirect:/uploader/login";
		}
		return "changePassword";
	}

	@RequestMapping(value = "/change-password", method = RequestMethod.POST)
	public @ResponseBody
	Response changePassword(@RequestParam(value = "oldPassword") String oldPassword,
			@RequestParam(value = "newPassword") String newPassword, Model model, HttpServletRequest request) {
		Response result = new Response();
		try {
			int id = ((Uploader) request.getSession().getAttribute("uploader")).getId();
			Uploader uploader = uploaderDao.getUploaderById(id);
			if (uploader == null) {
				result.setSuccess(false);
				result.setMsg("Bạn chưa đăng nhập. Vui lòng đăng nhập để thực hiện chức năng này");
				return result;
			}
			if (!oldPassword.isEmpty()) {
				oldPassword = CommonUtils.getMD5(oldPassword);
			}
			if (uploader.getPassword() != null && !uploader.getPassword().isEmpty()
					&& !oldPassword.equals(uploader.getPassword())) {
				result.setSuccess(false);
				result.setMsg("Mật khẩu không đúng. Vui lòng thử lại !!!");
				return result;
			}

			newPassword = uploaderDao.updatePassword(uploader.getId(), newPassword);
			if (newPassword.isEmpty()) {
				result.setSuccess(false);
				result.setMsg("Lỗi trong quá trình cập nhật mật khẩu. Vui lòng thử lại lần nữa!!!");
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	public @ResponseBody
	Response logout(SessionStatus status) {
		Response result = new Response();
		try {
			status.setComplete();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping(value = "/top-uploader/{type}", method = RequestMethod.GET)
	public @ResponseBody
	List<Uploader> getTopUploader(@PathVariable String type) {
		try {
			return uploaderDao.getTopUploader(type, 10);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value = "/top", method = RequestMethod.GET)
	public String getFullTopUploader(Model model, HttpServletRequest request) {
		String path = "";
		try {
			List<Uploader> ls = uploaderDao.getTopUploader("WEEK", 50);
			model.addAttribute("uploaders", ls);
			path = CommonUtils.getRootPathByDevice(DeviceUtils.getCurrentDevice(request));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return path + "topDanhHai";
	}

	@RequestMapping(value = "/top/{type}", method = RequestMethod.GET)
	public @ResponseBody
	List<Uploader> getFullTopUploader(@PathVariable String type, Model model) {
		try {
			return uploaderDao.getTopUploader(type, 50);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value = "/uploadAvatar", method = RequestMethod.POST)
	public @ResponseBody
	Response uploadFile(MultipartHttpServletRequest request, HttpServletResponse response) {
		Response result = new Response();
		Iterator<String> itr = request.getFileNames();
		MultipartFile mpf = null;

		while (itr.hasNext()) {

			mpf = request.getFile(itr.next());
			String fileType = mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf("."));
			Date date = new Date();
			String randomFileName = String.valueOf(date.getTime()) + String.valueOf(Math.random()).replace(".", "")
					+ fileType;
			String path = request.getSession().getServletContext().getRealPath("/") + Constant.AVATAR_PATH;
			path = path + "/" + randomFileName;
			try {
				FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(path));
				result.setData(request.getContextPath() + "/" + Constant.AVATAR_PATH + "/" + randomFileName);

			} catch (IOException e) {
				result.setSuccess(false);
				result.setMsg(e.getMessage());
				e.printStackTrace();
			}
		}
		return result;
	}

	@RequestMapping(value = "/update-info", method = RequestMethod.POST)
	public @ResponseBody
	Response updateInfo(@RequestParam(value = "name") String name, @RequestParam(value = "avatar") String avatar,
			@RequestParam(value = "description") String description, HttpServletRequest request) {
		Response result = new Response();
		try {
			Uploader uploader = (Uploader) request.getSession().getAttribute("uploader");
			if(uploader != null){
				if(avatar.isEmpty()){
					avatar = uploader.getAvatar();
				}
				uploaderDao.updateInfo(uploader.getId(), name, avatar, description);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}
